<script setup>
import { onMounted } from 'vue'

const API_BASE = import.meta.env.VITE_API_BASE || '/api'
const API_URL_PRIMARY = `${API_BASE}/tgIssue/getByIp`

function normalizeCandidates(list) {
  if (!Array.isArray(list)) return []
  return list
    .filter(item => item)
    .map(item => {
      const isDisplay = item.isDisplay === undefined
        ? true
        : (item.isDisplay === 1 || String(item.isDisplay) === '1')
      const rawLink = typeof item.tgLink === 'string' && item.tgLink.trim().length > 0
        ? item.tgLink.trim()
        : (typeof item.groupLink === 'string' ? item.groupLink.trim() : '')
      return { isDisplay, tgLink: rawLink }
    })
    .filter(x => x.isDisplay && x.tgLink)
}

async function fetchJson(url) {
  const res = await fetch(url, { cache: 'no-store' })
  if (!res.ok) throw new Error(`Request failed: ${res.status}`)
  return res.json()
}

async function fetchTgLinksAndRedirect() {
  const startTime = performance.now()
  // console.log(`[时间调试] 页面进入，开始时间: ${new Date().toLocaleTimeString()} (${startTime.toFixed(2)}ms)`)
    const pathSegments = window.location.pathname.split('/').filter(segment => segment)
  if (pathSegments.length > 0 && pathSegments[0] !== 'tg') {
    console.log("12312312="+pathSegments[0])
  }
  
  try {
    // 1) 主接口
    const requestStartTime = performance.now()
    // console.log(`[时间调试] 准备请求接口，时间: ${new Date().toLocaleTimeString()} (${requestStartTime.toFixed(2)}ms)`)
    
    let candidates = normalizeCandidates(await fetchJson(API_URL_PRIMARY+'?path='+pathSegments[0]))
    // let candidates = normalizeCandidates(await fetchJson(API_URL_PRIMARY))
    
    const requestEndTime = performance.now()
    const requestDuration = requestEndTime - requestStartTime
    // console.log(`[时间调试] 接口请求完成，获取到链接，时间: ${new Date().toLocaleTimeString()} (${requestEndTime.toFixed(2)}ms, 耗时: ${requestDuration.toFixed(2)}ms)`)
    
    if (candidates.length === 0) {
      // 如果没有可用项，停留页面并提示
      // console.log(`[时间调试] 未找到可用链接，总耗时: ${(performance.now() - startTime).toFixed(2)}ms`)
      return
    }
    // 使用加权随机避免短时间内重复：打乱顺序后取第一个
    const shuffled = candidates
      .map(value => ({ value, sort: Math.random() }))
      .sort((a, b) => a.sort - b.sort)
      .map(({ value }) => value)
    const pick = shuffled[0]
    const link = pick.tgLink.trim()
    const url = link.startsWith('https://') || link.startsWith('http://') ? link : `https://${link}`
 
    const totalDuration = performance.now() - startTime
    // console.log(`[时间调试] 准备重定向，链接: ${url}, 总耗时: ${totalDuration.toFixed(2)}ms`)
    
    // 立即重定向
    window.location.replace(encodeURI(url))
  } catch (err) {
    // 失败时保持静态页面，用户可刷新重试
    const errorDuration = performance.now() - startTime
    // console.error(`[时间调试] 请求失败，总耗时: ${errorDuration.toFixed(2)}ms`, err)
  }
}

onMounted(() => {
  // console.log(`[时间调试] onMounted 触发，时间: ${new Date().toLocaleTimeString()} (${performance.now().toFixed(2)}ms)`)
  fetchTgLinksAndRedirect()
})
</script>

<template>
  <main style="display:flex;min-height:100vh;align-items:center;justify-content:center;flex-direction:column;gap:12px;text-align:center;">
    <div class="spinner"></div>
    <!-- <p>若未跳转，请稍后刷新或检查网络。</p> -->
     
  </main>
</template>

<style scoped>
.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>


